package com.winter.main.controller.system;

import com.alibaba.fastjson.JSON;
import com.winter.main.constant.SystemConstant;
import com.winter.main.model.dto.NavigationDto;
import com.winter.main.model.entity.SysUser;
import com.winter.main.service.system.SysRuleService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Desc:
 * Author: dushuang
 * Date: Create in 2018/5/7
 */
@Controller
@RequestMapping("system/menu")
public class MenuController {

    private Logger logger = LogManager.getLogger(this);

    @Autowired
    private SysRuleService ruleService;

    @RequestMapping("/getNavigation")
    @ResponseBody
    public List<NavigationDto> getNavigationList(HttpServletRequest request){
        logger.info("查询用户菜单--开始...");
        List<NavigationDto> navigationList = new ArrayList<NavigationDto>();
        Subject subject = SecurityUtils.getSubject();
        SysUser user = (SysUser)subject.getSession().getAttribute(SystemConstant.SESSION_USER);
        // 父节点
        List<NavigationDto> rootMenu = ruleService.selectRootRule(user);
        // 子节点
        List<NavigationDto> childMenu = ruleService.selectChildRuleWithoutRoot(user);

        for (NavigationDto root : rootMenu){
            List<NavigationDto> childs = new ArrayList<>();
            Long rootId = root.getTargetId();
            for (NavigationDto child : childMenu){
                // 判断如果为该父节点的子节点
                Long parentId = child.getParentId();
                if(parentId.compareTo(rootId) == 0){
                    child.setUrl(request.getContextPath() + "/" + child.getUrl());
                    childs.add(child);
                }
            }
            root.setChildren(childs);
            navigationList.add(root);
        }
        logger.info("查询用户菜单--结束...");
        return navigationList;
    }



}
